/*
 Copyright (C) 2009 are of boxtorrents
 boxtorrents, azureus, vuze, and java are copyrighted to their respective owner.

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; version 2 of the License.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 */
package com.boxtorrents.azureus;

import java.net.MalformedURLException;
import java.net.URL;

import org.gudy.azureus2.plugins.PluginInterface;
import org.gudy.azureus2.plugins.download.Download;
import org.gudy.azureus2.plugins.torrent.TorrentAnnounceURLListSet;
import org.gudy.azureus2.plugins.torrent.TorrentAttribute;

/**
 * Provide various utilities function
 * 
 * @author are of boxtorrents
 */
public class Util {
	/**
	 * Check wheter supplied download is boxtorrent download or not.
	 * 
	 * @param download
	 * @return true if boxtorrents download, false otherwise
	 */
	public static boolean isBoxtorrentsDownload(Download download) {
		final TorrentAttribute attIsBox = getTorrentAttribute("isBoxtorrent");
		if (download.hasAttribute(attIsBox)
		    && download.getBooleanAttribute(attIsBox)) return true;
		return false;
	}

	/**
	 * Check wheter supplied download has boxtorrent as a tracker.
	 * 
	 * @param download
	 * @return true if has tracker boxtorrents, false otherwise
	 */
	public static boolean isBoxtorrentsTracker(Download download) {
		URL announceURL = download.getTorrent().getAnnounceURL();
		if (announceURL != null
		    && announceURL.getHost().indexOf("tracker.boxtorrents.com") >= 0) {
			return true;
		}
		TorrentAnnounceURLListSet[] sets = download.getTorrent()
		    .getAnnounceURLList().getSets();
		for (TorrentAnnounceURLListSet set : sets) {
			for (URL url : set.getURLs()) {
				if (url.getHost().indexOf("tracker.boxtorrents.com") >= 0) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * Find a string between 2 known string.
	 * 
	 * @param string original string
	 * @param before string before searched string
	 * @param after string after searched string
	 * @return substring between
	 */
	public static String substringBetween(String string, String before,
	    String after) {
		String result = null;
		final int firstmatch = string.indexOf(before) + before.length();
		if (firstmatch >= 0) {
			final int lastmatch = string.indexOf(after, firstmatch);
			if (lastmatch >= 0) {
				result = string.substring(firstmatch, lastmatch);
			}
		}
		return result;
	}

	/**
	 * Get torrent attribute, or register it as plugin attribute when it not
	 * defined
	 * 
	 * @param name
	 * @return registered TorrentAttribute
	 */
	public static synchronized TorrentAttribute getTorrentAttribute(String name) {
		final PluginInterface pi = BoxTorrentsPlugin.getPluginInterface();
		TorrentAttribute att = null;
		for (TorrentAttribute attribute : pi.getTorrentManager()
		    .getDefinedAttributes()) {
			if (attribute.getName().equals(name)) {
				att = attribute;
				break;
			}
		}

		if (att == null) att = pi.getTorrentManager().getPluginAttribute(name);
		return att;
	}

	private static char toHexChar(int i) {
		if ((0 <= i) && (i <= 9)) {
			return (char)('0' + i);
		}
		return (char)('a' + (i - 10));
	}

	/**
	 * @param data
	 * @return string value of binary data
	 */
	public static final String data2hex(byte[] data) {
		if (data == null) {
			return null;
		}
		final int len = data.length;
		final StringBuffer buf = new StringBuffer(len * 2);
		for (int pos = 0; pos < len; pos++) {
			buf.append(toHexChar((data[pos] >>> 4) & 15)).append(
			    toHexChar(data[pos] & 15));
		}
		return buf.toString();
	}

	/**
	 * @return box url
	 * @throws MalformedURLException if passkey not properly configured
	 */
	public static URL getBoxtorrentsTrackerURL() throws MalformedURLException {
		String passkey = BoxTorrentsPlugin.getPluginInterface().getPluginconfig()
		    .getPluginStringParameter(PluginParamConstants.PR_PASSKEY,
		        "user.passkey");
		return new URL("http://tracker.boxtorrents.com:2710/" + passkey
		    + "/announce.php");
	}

	/**
	 * @return alt URL
	 * @throws MalformedURLException
	 */
	public static URL getAlternativeTrackerURL() throws MalformedURLException {
		return new URL(BoxTorrentsPlugin.getPluginInterface().getPluginconfig()
		    .getPluginStringParameter(
		        PluginParamConstants.PR_DOWNLOAD_HANDLER_ALT_TRACKER,
		        "http://open.tracker.thepiratebay.org/announce"));
	}
}
